package com.syt.mina.session;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import org.apache.mina.core.session.IoSession;

import com.syt.mina.message.IMessage;

import flex.messaging.io.amf.ASObject;

public abstract class AbstractSessionManager implements ISessionManager {

	protected Map<String,IoSession> sessionMap = Collections.synchronizedMap(new HashMap<String,IoSession>());
	
	public void addSession(IoSession session){
		sessionMap.put(String.valueOf(session.getId()), session);
	}
	
	public void deleteSession(IoSession session){
		sessionMap.remove(String.valueOf(session.getId()));
	}

	@Override
	public Map<String, IoSession> getAllSession() {
		return sessionMap;
	}

	@Override
	public void broadcastMessage(IMessage message) {
		synchronized(sessionMap){
			for(IoSession session : sessionMap.values()){
				if(session.isConnected() && ! session.isWriterIdle()){
					session.write(message.getMessage());
				}
			}
		}
	}
	
	public void broadcastMessageAs(ASObject as) {
		synchronized(sessionMap){
			for(IoSession session : sessionMap.values()){
				if(session.isConnected() && ! session.isWriterIdle()){
					session.write(as);
				}
			}
		}
	}


	@Override
	public void sendMessageTo(IoSession session, IMessage message) {
		if(session!=null && session.isConnected()){
			session.write(message.getMessage());
		}
	}

	@Override
	public void sendMessageTo(String key, IMessage message) {
		IoSession session = (IoSession)sessionMap.get(key);
		sendMessageTo(session,message);
	}


}
